
#include <cstring>
#include "ObjMeta.h"
#include "vm.h"

ObjModule *ObjModule::NewObjModule(VM *vm, const char *modName) {
    auto *objModule = ALLOCATE(vm, ObjModule);
    if (objModule == nullptr) {
        MEM_ERROR("allocate ObjModule failed!");
    }

    //ObjModule是元信息对象,不属于任何一个类
    objModule->objHeader = *new ObjHeader(vm, OT_MODULE, nullptr);

    StringBufferInit(&objModule->moduleVarName);
    ValueBufferInit(&objModule->moduleVarValue);

    objModule->name = nullptr;   //核心模块名为NULL
    if (modName != nullptr) {
        objModule->name = new ObjString(vm, modName, strlen(modName));
    }

    return objModule;
}

ObjModule::ObjModule(VM *vm, const char *modName) {

    auto *objModule = ALLOCATE(vm, ObjModule);
    if (objModule == nullptr) {
        MEM_ERROR("allocate ObjModule failed!");
    }

    //ObjModule是元信息对象,不属于任何一个类
    objModule->objHeader = *new ObjHeader(vm, OT_MODULE, nullptr);

    StringBufferInit(&objModule->moduleVarName);
    ValueBufferInit(&objModule->moduleVarValue);

    objModule->name = nullptr;   //核心模块名为NULL
    if (modName != nullptr) {
        objModule->name = new ObjString(vm, modName, strlen(modName));
    }

    this->name = objModule->name;
    this->objHeader = objModule->objHeader;
    this->moduleVarName = objModule->moduleVarName;
    this->moduleVarValue = objModule->moduleVarValue;

}

ObjInstance *ObjInstance::NewObjInstance(VM *vm, Class *objClass) {
    //参数class主要作用是提供类中field的数目
    auto *objInstance = ALLOCATE_EXTRA(vm, ObjInstance, sizeof(Value) * objClass->fieldNum);

    //在此关联对象的类为参数class
    objInstance->objHeader = *new ObjHeader(vm, OT_INSTANCE, objClass);

    //初始化field为NULL
    uint32_t idx = 0;
    while (idx < objClass->fieldNum) {
        objInstance->fields[idx++] = VT_TO_VALUE(VT_NULL);
    }
    return objInstance;
}

ObjInstance::ObjInstance(VM *vm, Class *objClass) {

    //参数class主要作用是提供类中field的数目
    auto *objInstance = ALLOCATE_EXTRA(vm, ObjInstance, sizeof(Value) * objClass->fieldNum);

    //在此关联对象的类为参数class
    objInstance->objHeader = *new ObjHeader(vm, OT_INSTANCE, objClass);

    //初始化field为NULL
    uint32_t idx = 0;
    while (idx < objClass->fieldNum) {
        this->fields[idx++] = VT_TO_VALUE(VT_NULL);
    }

    this->objHeader = objInstance->objHeader;

}
